<template>
  <PageContainer>
    <Header :title="formData.id ? '编辑单位信息' : '添加单位信息'" />
    <view class="hb-p-4">
      <tm-form
        @submit="handleSubmit"
        layout="vertical"
        :model-value="formData"
        :margin="[0, 0]"
        :padding="[0, 0]"
        :border="false"
        :label-align="'top'"
        :transparent="true"
      >
        <view class="hb-bg-white hb-px-4 hb-py-3 hb-box-shadow-base hb-rounded-lg">
          <!-- 单位名称输入区域 -->
          <tm-form-item
            required
            field="companyId"
            label="单位名称"
            :border="false"
            :margin="[0, 0]"
            :rules="[
              {
                required: true,
                message: '请输入公司名称搜索，并选择',
                validator: () => {
                  if (formData.companyId && formData.name) {
                    return true;
                  }
                  return false;
                },
              },
            ]"
          >
            <InputSearch
              v-model:name="formData.name"
              placeholder="请输入公司名称搜索"
              @select="handleSelectCompany"
            />
          </tm-form-item>

          <!-- 单位logo上传区域 -->
          <tm-form-item
            field="logo"
            label="单位logo"
            :border="false"
            :margin="[0, 0]"
            :rules="[{ required: true, message: '请上传单位logo' }]"
          >
            <view class="hb-flex hb-items-center hb-gap-4">
              <TImage
                :src="formData.logo"
                width="160rpx"
                height="160rpx"
                border-radius="16rpx"
                error-img-type='unit'
              />
              <text
                class="hb-text-sm hb-text-[#2878FF] hb-py-1 hb-px-2 hb-inline-block hb-rounded-full hb-border hb-border-[#2878FF]"
                @click="handleUploadAvatar"
              >
                更换
              </text>
            </view>
          </tm-form-item>

          <!-- 单位职务输入区域 -->
          <tm-form-item
            required
            field="position"
            label="单位职务"
            :border="false"
            :margin="[0, 0]"
            :rules="[{ required: true, message: '请输入单位职务' }]"
          >
            <TmInput
              v-model="formData.position"
              :height="88"
              :font-size="28"
              placeholder="单位职务"
              :maxlength="20"
            />
          </tm-form-item>

          <!-- 单位介绍输入区域 -->
          <tm-form-item field="description" label="单位介绍" :border="false" :margin="[0, 0]">
            <TmInput
              v-model="formData.description"
              :height="160"
              :font-size="28"
              :inputPadding="[16, 16]"
              placeholder="用一段话介绍你的单位，让人更了解你"
              type="textarea"
            />
          </tm-form-item>

          <!-- 主营业务选择区域 -->
          <tm-form-item field="mainBusinessList" :border="false" :margin="[0, 0]">
            <template #label>
              <view class="hb-flex hb-items-center hb-justify-between hb-mb-3">
                <text class="hb-text-sm hb-text-[#333]">主营业务</text>
                <!-- 添加标签按钮 -->
                <tm-tag
                  label="+ 添加"
                  :round="6"
                  :fontSize="24"
                  :padding="[16, 12]"
                  color="#D0F7FF"
                  :font-color="'#2878FF'"
                  :follow-theme="false"
                  :margin="[0, 0]"
                  size="xs"
                  @click="handleAddTag"
                ></tm-tag>
              </view>
            </template>
            <view class="hb-flex hb-flex-wrap hb-gap-2">
              <!-- 已选标签 -->
              <view v-for="(item, index) in formData.mainBusinessList" :key="item">
                <tm-tag
                  :label="item"
                  :closable="true"
                  :round="4"
                  :fontSize="24"
                  color="#D0F7FF"
                  :font-color="'#2878FF'"
                  :follow-theme="false"
                  :margin="[0, 0]"
                  size="xs"
                  @click="handleTagClick(item, index)"
                  @close="removeTag(item)"
                ></tm-tag>
              </view>
            </view>
          </tm-form-item>

          <tm-form-item
            required
            field="address"
            label="单位地址"
            :border="false"
            :margin="[0, 0]"
            :rules="[{ required: true, message: '请选择单位地址' }]"
          >
            <tm-text :label="formData.address" :font-size="28" />
            <tm-button
              label="选择地址"
              :font-size="28"
              :padding="[0]"
              :width="200"
              :height="60"
              :round="6"
              icon="ali-icon icon-address"
              color="#2878FF"
              @click="handleAddressClick"
            ></tm-button>
          </tm-form-item>
        </view>
        <!-- 底部确认按钮 -->
        <BottomSubmit
          :submit-loading="loading"
          submitBtnLabel="保存"
          :submitBtnColor="'#2878FF'"
          cancelBtnLabel="删除"
          :hideCancelBtn="!formData.id"
          @cancel="handleDelete"
        />
      </tm-form>

      <tm-modal v-model:show="showModal" title="添加主营业务" :closeable="true">
        <view class="hb-flex hb-flex-col hb-gap-2 hb-py-3">
          <view class="hb-flex hb-items-center hb-text-sm">
            <text class="hb-text-[#333] hb-font-bold">主营业务</text>
            <text class="hb-text-red-500">*</text>
          </view>
          <tm-input v-model="tag" placeholder="请输入" :height="88" />
        </view>
        <template #button>
          <view class="hb-flex hb-justify-center hb-w-full">
            <tm-button
              :round="10"
              label="确认添加"
              :fontSize="32"
              style="width: 524rpx"
              :padding="[0, 24]"
              block
              color="#2878FF"
              @click="handleAddTagConfirm"
            ></tm-button>
          </view>
        </template>
      </tm-modal>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* companyInfoEdit 编辑单位信息 */
  import {
    addOrUpdateCompany,
    botUpdate,
    deleteCompany,
    getByIdInfo,
    getCompanyById,
    tianyanchaDetail,
  } from '@/api/card';
  import { BotCardInfo, BotCompanyInfo, TianyanchaResult } from '@/api/card/type';
  import InputSearch from './components/InputSearch.vue';

  import { useUpload } from '@/hooks/file/useUpload';
  import { FunctionArgs } from '@vueuse/core';
  import { useUserStore } from '@/store/modules/user';
  import { debounce } from 'lodash-es';
  const userStore = useUserStore();

  const showModal = ref(false);
  const tag = ref('');

  const { chooseFile, successResult, delResultItem } = useUpload();
  let success: FunctionArgs | undefined;
  let id: number | undefined;
  customOnload<'CardBasicInfo'>((options) => {
    success = options.success;
    id = options.id;
    queryCompanyById();
  });

  // 处理选择公司
  const handleSelectCompany = async (company: TianyanchaResult) => {
    formData.name = company.name;
    formData.companyId = company.id;
    if (company.id) {
      await tianyanchaDetail(company);
    }
  };

  const handleUploadAvatar = () => {
    chooseFile({
      mediaType: 'image',
    });
  };

  const queryCompanyById = async () => {
    if (!id) return;
    const res = await getCompanyById(id);
    formData.name = res.name;
    formData.logo = res.logo;
    formData.position = res.position;
    formData.mainBusinessList = res.mainBusinessList || [];
    formData.companyId = res.companyId;
    formData.id = res.id;
    formData.longitude = res.longitude;
    formData.latitude = res.latitude;
    formData.address = res.address;
    formData.addressName = res.addressName;
    formData.addressStr = res.addressStr;
    formData.description = res.description;
  };
  const updIndex = ref(-1);
  const handleTagClick = (item: string, index: number) => {
    tag.value = item;
    updIndex.value = index;
    showModal.value = true;
  };
  const handleAddressClick = () => {
    uni.chooseLocation({
      success: (res) => {
        formData.longitude = res.longitude as unknown as string;
        formData.latitude = res.latitude as unknown as string;
        formData.address = res.address;
        formData.addressName = res.name;
        formData.address = res.address;
      },
    });
  };

  watch(
    () => successResult,
    (res) => {
      if (res.value[0]) {
        formData.logo = res.value[0].filePath!;
        nextTick(() => {
          delResultItem(0);
        });
      }
    },
    {
      deep: true,
    },
  );

  const handleAddTag = () => {
    tag.value = '';
    updIndex.value = -1;
    showModal.value = true;
  };

  const handleAddTagConfirm = debounce(() => {
    if (!tag.value) {
      uni.showToast({
        title: '请输入主营业务',
        icon: 'none',
      });
      return;
    }

    if (formData.mainBusinessList.includes(tag.value)) {
      uni.showToast({
        title: '主营业务已存在',
        icon: 'none',
      });
      return;
    }

    if (updIndex.value === -1) {
      formData.mainBusinessList.push(tag.value);
    } else {
      formData.mainBusinessList[updIndex.value] = tag.value;
    }
    tag.value = '';
    updIndex.value = -1;
    showModal.value = false;
  }, 200);

  const removeTag = (item: string) => {
    formData.mainBusinessList = formData.mainBusinessList.filter((fitem) => fitem !== item);
  };

  const formData = reactive<BotCompanyInfo>({
    logo: '',
    name: '',
    position: '',
    mainBusinessList: [],
    companyId: undefined,
    longitude: '',
    latitude: '',
    address: '',
    addressName: '',
    addressStr: '',
    description: '',
  });
  const loading = ref(false);

  const handleSubmit = debounce(async (e: Tmui.tmFormSubmitResult<typeof formData>) => {
    try {
      // 表单验证
      if (!e.isPass) return;
      // 防止重复提交
      if (loading.value) return;
      loading.value = true;

      await addOrUpdateCompany(formData);
      userStore.getUserInfo();
      uni.showToast({
        title: '保存成功',
        icon: 'success',
      });
      setTimeout(() => {
        success?.();
        navigateBack();
      }, 1000);

      console.log('formData', formData);
    } catch (e) {
      console.error('表单验证失败', e);
    } finally {
      loading.value = false;
    }
  }, 200);
  const handleDelete = async () => {
    uni.showModal({
      title: '提示',
      content: '确定删除该单位信息吗？',
      success: async (res) => {
        if (res.confirm) {
          await deleteCompany(id!);
          uni.showToast({
            title: '删除成功',
            icon: 'success',
          });
          setTimeout(() => {
            success?.();
            navigateBack();
          }, 1000);
        }
      },
    });
  };
</script>

<style lang="scss" scoped></style>
